<?php

require __DIR__.'/vendor/autoload.php';

// 极简测试
class SimpleTreeConverter {
    public function convert($data) {
        $tree = [];
        foreach ($data as $item) {
            $parts = explode(',', $item['namePath']);
            if (count($parts) === 3) {
                list($l1, $l2, $l3) = array_map('trim', $parts);
                if (!isset($tree[$l1])) $tree[$l1] = [];
                if (!isset($tree[$l1][$l2])) $tree[$l1][$l2] = [];
                $tree[$l1][$l2][$l3] = $item;
            }
        }
        return $tree;
    }
    
    public function format($tree) {
        $output = "";
        foreach ($tree as $l1 => $l2s) {
            $output .= "{$l1}\n";
            foreach ($l2s as $l2 => $l3s) {
                $output .= "  {$l2}\n";
                foreach ($l3s as $l3 => $item) {
                    $output .= "    {$l3} (ID: {$item['id']})\n";
                }
            }
        }
        return $output;
    }
}

$data = [
    ["id" => 1, "name" => "空心菜类", "level" => 3, "namePath" => "蔬菜/豆制品,叶菜类,空心菜类"],
    ["id" => 2, "name" => "香菜类", "level" => 3, "namePath" => "蔬菜/豆制品,葱姜蒜椒/调味菜,香菜类"]
];

$converter = new SimpleTreeConverter();
$tree = $converter->convert($data);
echo $converter->format($tree);